package com.selangshiwo.sina.result;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.selangshiwo.Util;

public class ResultPack implements IResultPack{
	
	private String context = "";			//保存原文本
	private ResultType type = ResultType.HTML;			//原文本类型
	private Map<String , ?> json = null ;
	
	public ResultPack(){
		
	}
	
	private String getBody(){
		if(this.type == ResultType.HTML)
			//return Util.getHtmlBody(this.context) ;
			return this.context ;
		else
			return "";
	}
	
	private Object context2obj(){
		if(this.type == ResultType.JSON)
			return JSONObject.parse(this.context);
		else
			return null ;
	}
	
	@Override
	public ResultType getResultType() {
		return this.type;
	}

	@Override
	public JSONObject toJSON() {
		return (JSONObject) this.context2obj();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, ?> toMap() {
		return (Map<String , ?>)this.context2obj();
	}
 
	public void initAfter() throws Exception{
		
	}
	
	@Override
	public void init(String text, ResultType type) throws Exception{
		
		this.setContext(text);
		if(null == type){
			if(text.indexOf("<body>") > 0){	//通过判断第一个字符是否为"{"判断是html或者json
				type = ResultType.HTML ;
			}else if(text.indexOf("{") == 0){
				type = ResultType.JSON ;
			}else{
				type = ResultType.FN ;
			}
		}
		
		if(null != type){
			this.setType(type);
		}
		
		Util.debug(text);
		try{
			if(ResultType.HTML.equals(type)){
				String strBody = this.getBody();
				json = Util.string2map(strBody) ;
			}
			else if(ResultType.JSON.equals(type)){
				json = toMap() ;
			}else{
				json = Util.string2map(Util.getParams(text, 0));
			}
		}catch(Exception ex){
			Util.debug("回答数据无法直接转为json，需手动处理！");
		}
		
		initAfter();
	}

	
	public String getContext() {
		return context;
	}

	private void setContext(String context) {
		this.context = context;
	}

	public ResultType getType() {
		return type;
	}

	private void setType(ResultType type) {
		this.type = type;
	}

	public Map<String, ?> getJson() {
		return json;
	}

}
